package networks;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by g705353 on 10/28/2014.
 */

/**
 * Created with IntelliJ IDEA.
 * User: g705353
 * Date: 9/23/13
 * Time: 11:30 AM
 * To change this template use File | Settings | File Templates.
 */
public class FTPUploader {

    public void sendFTP(String hostname, String destDirectory, String username, String password, List<File> files){
        FTPClient ftp = new FTPClient();
        try {
            ftp.connect( hostname );
            String replyString = ftp.getReplyString();
            int replyCode = ftp.getReplyCode();
            System.out.println("connection info: " + replyCode + ", message: " + replyString);
            if( ! FTPReply.isPositiveCompletion(replyCode) ) {
                throw new Exception( "connection refused ==> code [" + replyCode + "], message[" + replyString + "]" );
            }
            ftp.login(username, password);
            //will throw a IOException if ftp fails to change directories
            if(!ftp.changeWorkingDirectory(destDirectory)) {
                throw new Exception("Could not change working directory to " + destDirectory);
            }

            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            System.out.println("Changed target dir to : " + destDirectory);
            for(File file : files) {
                String tempFileName = file.getName() + ".tmp";
                ftp.storeFile(tempFileName, new FileInputStream(file));
                System.out.println("temp file name is : " + tempFileName);
                ftp.rename(tempFileName, file.getName() + ".allen");
                System.out.println("temp file re-named to: " + file.getName() + ".allen");
//                ftp.storeFile(file.getName(), new FileInputStream(file));
            }
            ftp.logout();
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            if(ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch(IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        List <File> files = new ArrayList<File>();
        files.add(new File("E:\\Allen\\groovy", "Untitled.png"));
//        files.add(new File("E:\\Allen\\groovy", "Untitled.png"));
        FTPUploader ftp = new FTPUploader();
        ftp.sendFTP("ying.syniverse.com", "/export/home/awol290/nanjing", "awol290", "r0und2", files);
    }
}
